<?php
namespace Framework\Library;

class ArrayPaginator
{
    const FIRST_PAGE = 0; // 第一页

    public static function paginatorArrayResultToArray(array $arr, $dataKey, $current, $perPage)
    {
        $result = self::buildResult($arr, $current, $perPage);
        return array_merge(
            [$dataKey => $result->items],
            self::getPaginatorCursors($result->total_items, $result->current, $perPage)
        );
    }

    public static function buildResult($arr, $current, $perPage)
    {
        $obj = new \ArrayObject();
        $obj->total_items = count($arr);
        $obj->current = $current;
        $obj->items = array_slice($arr, ($current - 1) * $perPage, $perPage);

        return $obj;
    }

    /**
     * 按特定格式产生分页结果中的游标.
     */
    public static function getPaginatorCursors($total, $currentPage, $perPage)
    {
        $totalPage = ceil(intval($total) / intval($perPage));
        $currentPage = intval($currentPage);

        return [
            'total_number' => intval($total),
            'before' => $currentPage - 1,
            'current' => $currentPage,
            'total_page' => $totalPage,
            'next' => $totalPage <= $currentPage ? 0 : $currentPage + 1,
        ];
    }
}
